﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using UnwiseSource.Administration.ToolClasses;
using UnwiseSource.ServiceReference1;

namespace UnwiseSource.Administration
{
    public partial class CoursesTool : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            UserCredibility userCreds = (UserCredibility)Session["userCreds"];
            RedirectBackToLoginIfNotLogged(userCreds);

            GenerateCourses();
        }

        private void RedirectBackToLoginIfNotLogged(UserCredibility userCreds)
        {
            bool redirectBack = true;

            if (userCreds != null)
            {
                if (userCreds.Credible)
                {
                    redirectBack = false;
                }
            }

            if (redirectBack)
            {
                Response.Redirect("~/Administration/Login.aspx");
            }
        }

        private void GenerateCourses()
        {
            try
            {
                Service1Client client = new Service1Client();
                string accessKey = Helper.getconfigparam("SECID", "");

                var result = client.GetAdminCourses(accessKey, "BG").ToArray();

                UserCredibility currentUser = (UserCredibility)Session["userCreds"];
                Array.Sort(result, (first, second) => RightsChecker.GetRightsForCourse(second, currentUser).
                    CompareTo(RightsChecker.GetRightsForCourse(first, currentUser)));

                foreach (var course in result)
                {
                    GenereteCourse(course);
                }
            }
            catch (Exception exc)
            {
                Helper.LogErrorMsg(exc.Message);
            }
        }

        private void GenereteCourse(AdminCourse course)
        {
            string courseName = Taker.ValueOrEmptyString(course.CourseName);
            string created = Taker.ValueOrEmptyString(course.Created); ;
            string creator = Taker.ValueOrEmptyString(course.Creator);
            string modified = Taker.ValueOrEmptyString(course.Modified);
            string modifier = Taker.ValueOrEmptyString(course.Modifier);
            string numberOfLectures = course.NumberOfLectures.ToString();
            string ended = Taker.BoolValueToBGDaINe(course.Ended);

            UserCredibility currentUser = (UserCredibility)Session["userCreds"];
            Rights userRights = RightsChecker.GetRightsForCourse(course, currentUser);

            MyHtmlGenericControl courseHolder = new MyHtmlGenericControl("article");
            courseHolder.Attributes["class"] = "course_element";
            courseHolder.storedInfo = course;

            if (userRights == Rights.Guest)
            {
                courseHolder.Style["background-color"] = "rgb(150,150,150)";
                courseHolder.Style["border"] = "1px solid rgb(120,120,120)";
            }
            else if (userRights == Rights.Contributor)
            {
                courseHolder.Style["background-color"] = "rgb(40,160,150)";
                courseHolder.Style["border"] = "1px solid rgb(20,120,50)"; 
            }
            else if (userRights == Rights.Owner || userRights == Rights.Admin)
            {
                courseHolder.Style["background-color"] = "rgb(70,160,50)";
                courseHolder.Style["border"] = "1px solid rgb(50, 120, 30)"; 
            }

            HtmlGenericControl courseHeading = new HtmlGenericControl("h1");
            courseHeading.InnerText = courseName;
            courseHolder.Controls.Add(courseHeading);

            //the list that holds the info - created, creator ... etc.
            HtmlGenericControl courseDataList = new HtmlGenericControl("ul");

            //start first the spans with the text then the item
            HtmlGenericControl spanCreated = new HtmlGenericControl("span");
            spanCreated.InnerText = created;
            HtmlGenericControl createdItem = new HtmlGenericControl("li");
            createdItem.InnerText = "Създаден: ";
            createdItem.Controls.Add(spanCreated);

            courseDataList.Controls.Add(createdItem);

            HtmlGenericControl spanCreator = new HtmlGenericControl("span");
            spanCreator.InnerText = creator;
            HtmlGenericControl creatorItem = new HtmlGenericControl("li");
            creatorItem.InnerText = "Създател: ";
            creatorItem.Controls.Add(spanCreator);

            courseDataList.Controls.Add(creatorItem);

            HtmlGenericControl spanModified = new HtmlGenericControl("span");
            spanModified.InnerText = modified;
            HtmlGenericControl modifiedItem = new HtmlGenericControl("li");
            modifiedItem.InnerText = "Редактиран: ";
            modifiedItem.Controls.Add(spanModified);

            courseDataList.Controls.Add(modifiedItem);

            HtmlGenericControl spanModifier = new HtmlGenericControl("span");
            spanModifier.InnerText = modifier;
            HtmlGenericControl modifierItem = new HtmlGenericControl("li");
            modifierItem.InnerText = "Редактирал: ";
            modifierItem.Controls.Add(spanModifier);

            courseDataList.Controls.Add(modifierItem);
            //finished working with the list so insert it in the course - article
            courseHolder.Controls.Add(courseDataList);

            //The div that holds the buttons and the paragraph with lectures number
            HtmlGenericControl buttonsHolder = new HtmlGenericControl("div");
            buttonsHolder.Attributes["class"] = "element_btns_holder";
            

            HtmlGenericControl lecNumSpan = new HtmlGenericControl("span");
            lecNumSpan.InnerText = numberOfLectures;

            HtmlGenericControl numberOfLecturesParagraph = new HtmlGenericControl("p");
            numberOfLecturesParagraph.InnerText = "Брой лекции: ";
            numberOfLecturesParagraph.Controls.Add(lecNumSpan);

            buttonsHolder.Controls.Add(numberOfLecturesParagraph);

            HtmlGenericControl endedSpan = new HtmlGenericControl("span");
            endedSpan.Attributes["class"] = "endedSpan";
            endedSpan.InnerText = ended;

            HtmlGenericControl endedParagraph = new HtmlGenericControl("p");
            endedParagraph.InnerText = "Завършил: ";
            endedParagraph.Controls.Add(endedSpan);

            buttonsHolder.Controls.Add(endedParagraph);

            if (userRights > Rights.Guest)
            {
                HtmlAnchor buttonEdit = new HtmlAnchor();
                buttonEdit.InnerText = "Редактирай";
                buttonEdit.ServerClick += buttonEdit_ServerClick;

                buttonsHolder.Controls.Add(buttonEdit);
            }

            if (userRights == Rights.Owner || userRights == Rights.Admin)
            {
                HtmlAnchor buttonDelete = new HtmlAnchor();
                buttonDelete.InnerText = "Изтрий";
                buttonDelete.ServerClick += buttonDelete_ServerClick;
                buttonDelete.Attributes.Add("onclick", "javascript: return confirm('Сигурни ли сте, че искате да изтриете курса?');");

                buttonsHolder.Controls.Add(buttonDelete);
            }

            courseHolder.Controls.Add(buttonsHolder);

            CoursesHolder.Controls.Add(courseHolder);
        }

        private static AdminCourse RetrieveCourse(object sender)
        {
            HtmlAnchor theBtn = sender as HtmlAnchor;
            HtmlGenericControl btnsHolder = theBtn.Parent as HtmlGenericControl;
            MyHtmlGenericControl courseHolder = btnsHolder.Parent as MyHtmlGenericControl;

            AdminCourse theCourse = courseHolder.storedInfo as AdminCourse;
            return theCourse;
        }

        void buttonDelete_ServerClick(object sender, EventArgs e)
        {
            AdminCourse theCourse = RetrieveCourse(sender);
            string accessKey = Helper.getconfigparam("SECID", "");

            Service1Client client = new Service1Client();
            client.DeleteCourse(accessKey, theCourse.CourseId);

            Response.Redirect(Request.RawUrl);
        }

        void buttonEdit_ServerClick(object sender, EventArgs e)
        {
            AdminCourse theCourse = RetrieveCourse(sender);

            Response.Redirect("~/Administration/CourseManagement.aspx?cId=" + theCourse.CourseId);
        }

        protected void btnNewCourse_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Administration/CourseManagement.aspx");
        }


    }
}